import { each } from 'lodash';
import { message } from 'antd';
import getPinyin from '../../../utils/getPy';
import utils from '../../../utils';
import { WeaLocaleProvider } from "ecCom";
import { runCommand } from ".";
const getLabel = WeaLocaleProvider.getLabel;


export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        runCommand(context, options, isUndo, (sheet, options) => {
            const { sheetIndex, sheetName, selections, mainTableObj,
                getDetailIndex, getFieldIndex, getFieldCellType, getFieldName, includeTitle } = options;
            const mainTable = `mainTable_${sheetIndex}`;
            selections.forEach(selection => {
                let { row, col, rowCount, colCount } = selection;
                // 只选择一行，且包含标题时，需要再增加一行
                if (rowCount == 1 && includeTitle === '1') {
                    rowCount = 2;
                }
                const removeTableFunc = [];
                options.oldTable = [];
                let colName = {};
                for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                    const currentRow = row + rowIndex;
                    for (let colIndex = 0; colIndex < colCount; colIndex++) {
                        const currentCol = col + colIndex;
                        const table = sheet.tables.find(currentRow, currentCol);
                        if (rowIndex == 0) {
                            colName[currentRow + "@" + currentCol] = sheet.getValue(currentRow, currentCol);
                        }
                        if (table) {
                            if (table.bindingPath() || table.name().startsWith('custom')) {
                                message.error(getLabel('512011','已存在明细表'));
                                return;
                            } else {
                                const tableJSON = table.toJSON();
                                if (options.oldTable.filter(d => d.row === tableJSON.row && d.col === tableJSON.col).length === 0) {
                                    options.oldTable.push(table.toJSON());
                                    removeTableFunc.push(() => {
                                        sheet.tables.remove(table.name(), GC.Spread.Sheets.Tables.TableRemoveOptions.none);
                                    })
                                }
                            }
                            // return;
                        }
                    }
                }
                removeTableFunc.forEach(func => func());
                const detailIndex = getDetailIndex(mainTable, sheet);
                const detail = `detail_${detailIndex}`;
                const columnLabels = [];
                for (let index = 0; index < colCount; index++) {
                    const fieldIndex = getFieldIndex(mainTable, detail);
                    let label = ((sheet.getValue(row, col + index) || '') + '').trim().replace(/[\r|\n]/g,"");
                    if (!label) {
                        label = ((colName[row + "@" + (col + index)] || '') + '').trim();
                        if (!label) {
                            label = `${getLabel(502711, '字段') + fieldIndex}`;
                        }
                    }
                    columnLabels.push({
                        fieldIndex,
                        label
                    });
                }
                const table = sheet.tables.add(`detail${detailIndex}`, row, col, rowCount, colCount, undefined, { showHeader: includeTitle === '1' });
                table.filterButtonVisible(false);
                const detailFields = [];
                table.bindingPath(`${sheetName}.${detail}`);
                const { row: dataRow, col: dataCol, colCount: tableColCount } = table.dataRange();
                for (let index = 0; index < tableColCount; index++) {
                    let { label, fieldIndex } = columnLabels[index];
                    let fieldName = getPinyin(label)[0];
                    if (!fieldName) {
                        fieldName = `field${fieldIndex}`;
                    }
                    fieldName = getFieldName(mainTable, detail, fieldName).toLowerCase();
                    table.setColumnDataField(index, fieldName);
                    table.setColumnName(index, label);

                    detailFields.push({
                        col: dataCol + index,
                        colCount: 1,
                        fieldName,
                        fieldType: ['input', 'text', '200'],
                        label,
                        row: dataRow,
                        rowCount: 1,
                        detailIndex,
                        uuid: utils.UUID()
                    });
                }

                mainTableObj.detailTables.push({
                    ...table.range(),
                    detailIndex,
                    fields: detailFields,
                });
                const columns = detailFields.map(field => (
                    new GC.Spread.Sheets.Tables.TableColumn(field.fieldName).name(field.label).dataField(field.fieldName)
                ));
                table.bindColumns(columns);
                detailFields.forEach((detailField, detailFieldIndex) => {
                    const fieldCellType = getFieldCellType(detailField);
                    sheet.getCell(detailField.row, detailField.col)
                        .textIndent(2.5)
                        .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                        .backgroundImage(fieldCellType.getFieldTypeImage())
                        .cellType(fieldCellType);

                });
            });
        })
    }
};
/* export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        const { sheet, sheetIndex, sheetName, selections, mainTableObj,
            getDetailIndex, getFieldIndex, getFieldCellType, getFieldName, includeTitle } = options;
        sheet.suspendPaint();
        try {
            if (isUndo) {
                selections.forEach(selection => {
                    const { row, col } = selection;
                    sheet.removeSpan(row, col);
                    sheet.tables.remove(sheet.tables.find(row + 1, col), GC.Spread.Sheets.Tables.TableRemoveOptions.none);
                });
                options.oldTable.forEach(table => {
                    const { name, row, col, rowCount, colCount, rowFilter: { filterButtonVisibleInfo } } = table;
                    const newTable = sheet.tables.add(name, row, col, rowCount, colCount);
                    newTable.filterButtonVisible(false);
                    const columns = table.columns.map(col => {
                        return new GC.Spread.Sheets.Tables.TableColumn(col.key).name(col.name);
                    });
                    newTable.bindColumns(columns);
                    each(filterButtonVisibleInfo, (value, key) => {
                        newTable.filterButtonVisible(key, value);
                    });
                })
                selections.forEach(selection => {
                    const { row, col, rowCount, colCount } = selection;
                    for (let currentRow = row, i = 0; i < rowCount; i++ , currentRow++) {
                        for (let currentCol = col, j = 0; j < colCount; currentCol++ , j++) {
                            sheet.getCell(currentRow, currentCol)
                                .cellType(options._oldCellTypes[currentRow][currentCol])
                                .text(options._oldCellText[currentRow][currentCol])
                                .backColor(options._oldBackColor[currentRow][currentCol])
                                .locked(options._oldLocked[currentRow][currentCol])
                                .textIndent(options._oldTextIndent[currentRow][currentCol])
                                .backgroundImageLayout(options._oldBackgroundImageLayout[currentRow][currentCol])
                                .backgroundImage(options._oldBackGroundImage[currentRow][currentCol]);
                        }
                    }
                });


            } else {


                const mainTable = `mainTable_${sheetIndex}`;
                options._oldBackColor = {};
                options._oldCellText = {};
                options._oldCellTypes = {};
                options._oldBackGroundImage = {};
                options._oldBackgroundImageLayout = {};
                options._oldTextIndent = {};
                options._oldTag = {};
                options._oldLocked = {};
                selections.forEach(selection => {
                    let { row, col, rowCount, colCount } = selection;
                    // 只选择一行，且包含标题时，需要再增加一行
                    if (rowCount == 1 && includeTitle === '1') {
                        rowCount = 2;
                    }
                    for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                        const currentRow = row + rowIndex;
                        if (!options._oldCellText[currentRow]) {
                            options._oldCellText[currentRow] = {};
                        }
                        if (!options._oldBackColor[currentRow]) {
                            options._oldBackColor[currentRow] = {}
                        }
                        if (!options._oldCellTypes[currentRow]) {
                            options._oldCellTypes[currentRow] = {};
                        }
                        if (!options._oldTextIndent[currentRow]) {
                            options._oldTextIndent[currentRow] = {};
                        }
                        if (!options._oldBackGroundImage[currentRow]) {
                            options._oldBackGroundImage[currentRow] = {};
                        }
                        if (!options._oldBackgroundImageLayout[currentRow]) {
                            options._oldBackgroundImageLayout[currentRow] = {};
                        }
                        if (!options._oldLocked[currentRow]) {
                            options._oldLocked[currentRow] = {};
                        }
                        for (let colIndex = 0; colIndex < colCount; colIndex++) {
                            const currentCol = col + colIndex;
                            const cell = sheet.getCell(currentRow, currentCol);
                            options._oldBackColor[currentRow][currentCol] = cell.backColor();
                            options._oldCellText[currentRow][currentCol] = cell.text();
                            options._oldCellTypes[currentRow][currentCol] = cell.cellType();
                            options._oldTextIndent[currentRow][currentCol] = cell.textIndent();
                            options._oldBackGroundImage[currentRow][currentCol] = cell.backgroundImage();
                            options._oldBackgroundImageLayout[currentRow][currentCol] = cell.backgroundImageLayout();
                            options._oldLocked[currentRow][currentCol] = cell.locked();
                        }
                    }

                    const removeTableFunc = [];
                    options.oldTable = [];
                    let colName = {};
                    for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                        const currentRow = row + rowIndex;
                        for (let colIndex = 0; colIndex < colCount; colIndex++) {
                            const currentCol = col + colIndex;
                            const table = sheet.tables.find(currentRow, currentCol);
                            if (rowIndex == 0) {
                                colName[currentRow + "@" + currentCol] = sheet.getValue(currentRow, currentCol);
                            }
                            if (table) {
                                if (table.bindingPath()) {
                                    message.error(getLabel('512011','已存在明细表'));
                                    return;
                                } else {
                                    const tableJSON = table.toJSON();
                                    if (options.oldTable.filter(d => d.row === tableJSON.row && d.col === tableJSON.col).length === 0) {
                                        options.oldTable.push(table.toJSON());
                                        removeTableFunc.push(() => {
                                            sheet.tables.remove(table.name(), GC.Spread.Sheets.Tables.TableRemoveOptions.none);
                                        })
                                    }
                                }
                                // return;
                            }
                        }
                    }
                    removeTableFunc.forEach(func => func());
                    const detailIndex = getDetailIndex(mainTable, sheet);
                    const detail = `detail_${detailIndex}`;
                    const columnLabels = [];
                    for (let index = 0; index < colCount; index++) {
                        const fieldIndex = getFieldIndex(mainTable, detail);
                        let label = ((sheet.getValue(row, col + index) || '') + '').trim();
                        if (!label) {
                            label = ((colName[row + "@" + (col + index)] || '') + '').trim();
                            if (!label) {
                                label = `${getLabel(502711, '字段') + fieldIndex}`;
                            }

                        }
                        columnLabels.push({
                            fieldIndex,
                            label
                        });
                    }
                    const table = sheet.tables.add(`detail${detailIndex}`, row, col, rowCount, colCount, undefined, { showHeader: includeTitle === '1' });
                    table.filterButtonVisible(false);
                    const detailFields = [];
                    table.bindingPath(`${sheetName}.${detail}`);
                    const { row: dataRow, col: dataCol, colCount: tableColCount } = table.dataRange();
                    for (let index = 0; index < tableColCount; index++) {
                        let { label, fieldIndex } = columnLabels[index];
                        let fieldName = getPinyin(label)[0];
                        if (!fieldName) {
                            fieldName = `field${fieldIndex}`;
                        }
                        fieldName = getFieldName(mainTable, detail, fieldName).toLowerCase();
                        table.setColumnDataField(index, fieldName);
                        table.setColumnName(index, label);

                        detailFields.push({
                            col: dataCol + index,
                            colCount: 1,
                            fieldName,
                            fieldType: ['input', 'text', '200'],
                            label,
                            row: dataRow,
                            rowCount: 1,
                            detailIndex
                        });
                    }

                    mainTableObj.detailTables.push({
                        ...table.range(),
                        detailIndex,
                        fields: detailFields,
                    });
                    const columns = detailFields.map(field => (
                        new GC.Spread.Sheets.Tables.TableColumn(field.fieldName).name(field.label).dataField(field.fieldName)
                    ));
                    table.bindColumns(columns);
                    detailFields.forEach((detailField, detailFieldIndex) => {
                        const fieldCellType = getFieldCellType(detailField);
                        sheet.getCell(detailField.row, detailField.col)
                            .textIndent(2.5)
                            .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                            .backgroundImage(fieldCellType.getFieldTypeImage())
                            .cellType(fieldCellType);

                    });
                });
            }
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
        sheet.resumePaint();
    }
}; */